package com.zhao.reggie3.controller;

import com.zhao.reggie3.common.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @description:
 * @author: zhao
 * @time: 2022/8/19 22:11
 */
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String basepath;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){

        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件名后缀 .jpg
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String uuidfilename = UUID.randomUUID().toString()+substring;
        //给指定的路径创建文件存放目录
        File dir = new File(basepath);

        if (!dir.exists()){
            dir.mkdirs();
        }

        //将临时文件转存到指定位置
        try {
            file.transferTo(new File(basepath+uuidfilename));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return R.success(uuidfilename);
    }
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            //从硬盘中读取文件
            FileInputStream fis = new FileInputStream(new File(basepath+name));
            //获取输出流
            ServletOutputStream fos = response.getOutputStream();
            //设置响应数据格式
            response.setContentType("image/jpeg");
            //IOUtils.copy(fis,fos);
            int len = 0;
            byte[] bytes = new byte[1024*8];
            while ((len= fis.read(bytes))!=-1){
                fos.write(bytes,0,len);
                fos.flush();
            }
            fos.close();
            fis.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}